<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.username" clearable size="small" placeholder="输入账号名" style="width: 200px;"
                  class="filter-item" @keyup.enter.native="crud.toQuery"/>
        <el-select v-model="query.enabled" clearable size="small" placeholder="状态" class="filter-item"
                   style="width: 90px" @change="crud.toQuery">
          <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"
          />
        </el-select>
        <rrOperation/>
      </div>
      <crudOperation show="" :permission="permission"/>
    </div>
    <!--    添加和编辑-->
    <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU"
               :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="570px">
      <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="66px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" @keydown.native="keydown($event)"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password @keydown.native="keydown($event)"/>
        </el-form-item>
        <el-form-item label="公司" prop="companyId">
          <el-select
            v-model="companyId"
            style="width: 178px"
            placeholder="请选择"
            @change="changeCompany"
          >
            <el-option
              v-for="item in companys"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.enabled" :disabled="form.id === user.id">
            <el-radio
              v-for="item in this.user_status"
              :key="item.id"
              :label="item.value"
            >{{ item.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item style="margin-bottom: 0;" label="角色" prop="rids">
          <el-select
            v-model="roleDatas"
            style="width: 437px"
            multiple
            placeholder="请选择"
            @remove-tag="deleteTag"
            @change="changeRole"
          >
<!--            :disabled="level !== 1 && item.level <= level"-->
            <el-option
              v-for="item in roles"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;"
              @selection-change="crud.selectionChangeHandler">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="username" label="登录账号"/>
      <el-table-column prop="companyName" label="所属公司"/>
      <el-table-column prop="roles" label="角色信息" :formatter="questionData"/>
      <el-table-column prop="enabled" label="状态" align="center">

        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.enabled"
            active-value="true"
            inactive-value="false"
            active-color="#409EFF"
            inactive-color="#F56C6C"
            @change="changeEnabled(scope.row, scope.row.enabled)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建日期"/>
      <el-table-column prop="createBy" label="创建人"/>
<!--      <el-table-column prop="updateTime" label="更新时间"/>-->
<!--      <el-table-column prop="updateBy" label="更新人"/>-->
      <el-table-column prop="lastLoginTime" label="上次登录时间"/>
      <!--   编辑与删除
        -->
      <el-table-column
        v-if="checkPer(['admin','user:edit','user:del'])"
        label="操作"
        width="130px"
        align="center"
        fixed="right"
      >
        <template slot-scope="scope">
          <udOperation
            :data="scope.row"
            :permission="permission"
          />
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination/>
  </div>
</template>

<script>
import crudUser from '@/api/system/user'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import { getAll } from '@/api/system/role'
import { getAllCompany } from '@/api/system/company'
import crudOperation from '@crud/CRUD.operation'
import pagination from '@crud/Pagination'
import rrOperation from '@crud/RR.operation'
import udOperation from '@crud/UD.operation'
import { mapGetters } from 'vuex'

let userRoles = []
let cid = ''
const defaultForm = { id: null, username: null, password: null, companyId: null, roles: null, enabled: 'true' }
export default {
  name: 'User',
  components: { crudOperation, pagination, rrOperation, udOperation },
  cruds() {
    return CRUD({
      title: '用户管理',
      url: 'api/users',
      crudMethod: { ...crudUser }
    })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      height: document.documentElement.clientHeight - 180 + 'px;',
      roleDatas: [], // 多选时使用
      companyId: '',
      level: 3,
      roles: [],
      companys: [],
      user_status: [
        { id: 1, label: '启用', value: 'true' },
        { id: 2, label: '禁用', value: 'false' }
      ],
      permission: {
        add: ['admin', 'user:add'],
        edit: ['admin', 'user:edit'],
        del: ['admin', 'user:del']
      },
      enabledTypeOptions: [
        { key: 'true', display_name: '正常' },
        { key: 'false', display_name: '禁用' }
      ],
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  methods: {
    questionData(row) {
      const arr = []
      row.roles.forEach((item, index) => {
        if (index > 2) {
          return
        }
        arr.push(item.name)
      })
      return arr.join(',')
    },
    // 改变状态
    changeEnabled(data, val) {
      this.$confirm('此操作将 ' + data.username + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudUser.edit(data).then(res => {
          this.crud.notify('成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.enabled = !data.enabled
        })
      }).catch(() => {
        data.enabled = !data.enabled
      })
    },

    // 禁止输入空格
    keydown(e) {
      if (e.keyCode === 32) {
        e.returnValue = false
      }
    },
    changeRole(value) {
      userRoles = []
      value.forEach(function(data, index) {
        // const role = { id: data }
        userRoles.push(data)
      })
    },
    changeCompany(value) {
      cid = value
    },
    deleteTag(value) {
      userRoles.forEach(function(data, index) {
        if (data.id === value) {
          userRoles.splice(index, value)
        }
      })
    },

    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      this.getRoles()
      this.getCompanys()
      form.password = ''
      form.enabled = form.enabled.toString()
    },
    // 新增前将多选的值设置为空
    [CRUD.HOOK.beforeToAdd]() {
      this.roleDatas = []
      this.companyId = ''
    },
    // 初始化编辑时候的角色与岗位
    [CRUD.HOOK.beforeToEdit](crud, form) {
      this.roleDatas = []
      this.companyId = ''
      // this.companys = []
      userRoles = []
      cid = ''
      const _this = this
      // 编辑事选中角色
      form.roles.forEach(function(role, index) {
        _this.roleDatas.push(role.id)
        userRoles.push(role.id)
      })
      // 选中公司
      this.companyId = form.companyId
      cid = form.companyId
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (this.roleDatas.length === 0) {
        this.$message({
          message: '角色不能为空',
          type: 'warning'
        })
        return false
      }
      // crud.form.roles = userRoles
      const rids = userRoles.join(',')
      crud.form.rids = rids
      crud.form.companyId = cid
      return true
    },
    // 获取弹窗内角色数据
    getRoles() {
      getAll().then(res => {
        this.roles = res
      }).catch(() => {
      })
    },
    getCompanys() {
      getAllCompany().then(res => {
        this.companys = res.content
      }).catch(() => {
      })
    },
    checkboxT(row, rowIndex) {
      return row.id !== this.user.id
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}
</style>
